package com.mayikt.edu.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mayikt.edu.constant.MayiktConstants;
import com.mayikt.edu.core.cache.LocalCache;
import com.mayikt.edu.dto.req.EduCourseReqDto;
import com.mayikt.edu.dto.resp.EduCourseRespDTO;
import com.mayikt.edu.entity.EduCourse;
import com.mayikt.edu.mapper.EduCourseMapper;
import com.mayikt.edu.service.IEduCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 课程表 服务实现类
 *
 * @author mayikt
 * @since 2023-10-12
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse>
        implements IEduCourseService {
    @Autowired
    private EduCourseMapper eduCourseMapper;

    @Override
    public List<EduCourse> getAllEduCourse() {
        QueryWrapper<EduCourse> eduCourseQueryWrapper = new QueryWrapper<>();
        return eduCourseMapper.selectList(eduCourseQueryWrapper);
    }

    /*
    基于内存查找数据
     */
    @Override
    public List<EduCourseRespDTO> searchCacheCourseList(EduCourseReqDto eduCourseRespDTO) {
        // 1，从内存中查找到所有课程列表
        List<EduCourseRespDTO> eduCourseRespList = new ArrayList<>();
        eduCourseRespList = LocalCache.get(MayiktConstants.COURSE_EDUCOURSERESPLIST, eduCourseRespList);
        if (CollectionUtils.isEmpty(eduCourseRespList)) {
            log.error("[从缓存中为查找到eduCourseRespList数据]");
            return null;
        }
        // 2基于内存查找数据
        Stream<EduCourseRespDTO> stream = eduCourseRespList.stream();
        String courseName = eduCourseRespDTO.getCourseName();
        Integer subjectId = eduCourseRespDTO.getSubjectId();
        if (!StringUtils.isBlank(courseName)) {
            //  stream = stream.filter((c) -> c.getCourseName().equals(courseName));
            //基于内存模糊查询数据
            stream = stream.filter(c ->
                    StrUtil.containsIgnoreCase(c.getCourseName(), (courseName)));
        }
        if (subjectId != null) {
            stream = stream.filter((c) -> c.getSubjectId().equals(subjectId));
        }
        // 流数据根据时间排序，放回对应的集合
        // 根据最后更新时间排序，返回对应的List集合

        return stream
                .sorted(Comparator.comparing(EduCourseRespDTO::getUpdateTime))
                .collect(Collectors.toList());
    }
}
